<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入组名称" v-model="listQuery.groupName"></el-input>
      <el-button class="filter-item" type="primary" style="float:right;"  icon="el-icon-edit"  @click="handleCreate">新增</el-button>
      <el-button class="filter-item" type="primary" style="float:right;margin-right:10px;" v-waves icon="el-icon-search" @click="handleFilter">查询</el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="正在加载中" border fit highlight-current-row
      style="width: 100%">
      <el-table-column align="center" label="行号" width="65">
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="组名称">
        <template slot-scope="scope">
          <span>{{scope.row.groupName }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="日期">
        <template slot-scope="scope">
          <span>{{scope.row.gmtCreate | formatDatetime}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="50px" label="终端数">
        <template slot-scope="scope">
          <span class="link-type" >{{scope.row.number}}</span>
        </template>
      </el-table-column>
      <el-table-column width="200px" align="center" label="描述">
        <template slot-scope="scope">
          <span>{{scope.row.remark}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="500" class-name="small-padding fixed-width">
        <template slot-scope="scope">
         <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
         <el-button type="success" size="mini" @click="handleDetail(scope.row)">详情</el-button>
         <el-button type="primary" size="mini" @click="terminalDetailAllocation(scope.row)">终端详情</el-button>
         <el-button type="success" size="mini" @click="terminalAllocation(scope.row)">终端分组</el-button>
         <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="90px" style='width: 450px; margin-left:50px;'>
        <el-input type="hidden" v-model="temp.id"></el-input>
        <el-form-item label="组名称" prop="groupName">
          <el-input v-model="temp.groupName"></el-input>
        </el-form-item>
        <el-form-item label="remark" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Please input" v-model="temp.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">cancel</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">confirm</el-button>
        <el-button v-else type="primary" @click="updateData">confirm</el-button>
      </div>
    </el-dialog>


    <el-dialog title="detail" :visible.sync="dialogDetailVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="90px" style='width: 450px; margin-left:50px;'>
       <el-input type="hidden" v-model="temp.id"></el-input>
        <el-form-item label="组名称" prop="groupName">
          <el-input v-model="temp.groupName"></el-input>
        </el-form-item>
        <el-form-item label="remark" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Please input" v-model="temp.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogDetailVisible = false">CLOSE</el-button>
      </span>
    </el-dialog>

    <el-dialog title="终端分组" :visible.sync="dialogAllocationVisible">
          <div class="filter-container">
      <el-input @keyup.enter.native="handleFilterN" style="width: 200px;" class="filter-item" placeholder="请输入硬件序列号" v-model="listQuery.equipmentId"></el-input>
      <el-button class="filter-item" type="primary" style="float:right;margin-right:10px;" v-waves icon="el-icon-search" @click="handleFilter">查询</el-button>
    </div>
    <el-table :key='tableKey' :data="listN" v-loading="listLoadingN" element-loading-text="正在加载中" border fit highlight-current-row
      style="width: 100%" @selection-change="handleSelectionChange">>
        <el-table-column align="center" label="行号" type="selection" width="65">
        </el-table-column>
        <el-table-column width="150px" align="center" label="硬件序列号">
          <template slot-scope="scope">
            <span>{{scope.row.equipmentId }}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="厂商">
          <template slot-scope="scope">
            <span>{{scope.row.equipmentPro}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="终端型号">
          <template slot-scope="scope">
            <span>{{scope.row.equipmentType}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChangeN" @current-change="handleCurrentChangeN" :current-page="listQueryN.page" :page-sizes="[10,20,30, 50]" :page-size="listQueryN.limit" layout="total, sizes, prev, pager, next, jumper" :total="totalN">
        </el-pagination>
    </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogAllocationVisible = false">CLOSE</el-button>
        <el-button  type="primary" @click="saveGroupEquipment">保存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="终端详情" :visible.sync="dialogAllocationDetailVisible">
          <div class="filter-container">
      <!-- <el-input @keyup.enter.native="handleFilterN" style="width: 200px;" class="filter-item" placeholder="请输入硬件序列号" v-model="listQuery.equipmentId"></el-input> -->
      <!-- <el-button class="filter-item" type="primary" style="float:right;margin-right:10px;" v-waves icon="el-icon-search" @click="handleFilter">查询</el-button> -->
    </div>
    <el-table :key='tableKey' :data="listdetail" v-loading="listLoadingdetail" element-loading-text="正在加载中" border fit highlight-current-row
      style="width: 100%" >
        <el-table-column align="center" label="行号" width="65">
            <template slot-scope="scope">
              <span>{{scope.$index+1}}</span>
            </template>
        </el-table-column>
        <el-table-column width="150px" align="center" label="硬件序列号">
          <template slot-scope="scope">
            <span>{{scope.row.equipmentId }}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="厂商">
          <template slot-scope="scope">
            <span>{{scope.row.equipmentPro}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="终端型号">
          <template slot-scope="scope">
            <span>{{scope.row.equipmentType}}</span>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogAllocationDetailVisible = false">CLOSE</el-button>
        <!-- <el-button  type="primary" @click="saveGroupEquipment">保存</el-button> -->
      </span>
    </el-dialog>


  </div>
</template>

<script>
import { getGroupList, saveGroup, updateGroup, getGroupDetail, deleteItimsGroup, saveEquipmentGroupList } from '@/api/itims/itimsgroup'
import { getTerminalList, getTerminalListByGroupId} from '@/api/itims/itimsterminal'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime, formatDate, formatDatetime  } from '@/utils'

export default {
  name: 'itimsbusiness',
  directives: {
    waves
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        groupName: undefined,
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      temp: {
        id: undefined,
        groupName: undefined,
        remark: '',
        isDeleted: 0,
        gmtCreate: null,
        gmtModified: null
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogDetailVisible:false,
      dialogAllocationVisible:false,
      pvData: [],
      rules: {
        groupName: [{ required: true, message: 'groupName is required', trigger: 'change' }]
      },
      multipleSelection: [],
      listN: null,
      totalN: null,
      listLoadingN: true,
      listQueryN: {
        groupName: undefined,
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
       },
       groupId:undefined,
       dialogAllocationDetailVisible: false,
       listdetail:[],
       listLoadingdetail:[]


    }
  },
  filters: {
    formatDate(time) {
       var date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd hh:mm');
    },
    formatDatetime(time){
      return formatDatetime(time);
    }

  },
  created() {
    this.getList()

  },
  methods: {
    getList() {
      this.listLoading = true
      const param = {
        'body': {
          "itimsGroupDTO":{
            "groupName":this.listQuery.groupName
          },
          "pageInfo":{
            "page":this.listQuery.page,
            "pageSize":this.listQuery.limit
          }
        }
      }
      getGroupList(param).then(response => {
        this.list = response.body.itimsGroupDTOList
        this.total = response.body.pageInfo.rowCount
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        groupName: undefined,
        remark: '',
        isDeleted: 0,
        gmtCreate: null,
        gmtModified: null
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const data = {
            'body': {
              "itimsGroupDTO":{
                //"id": this.temp.id,
                "groupName": this.temp.groupName,
                "isDeleted":"0",
                "remark": this.temp.remark
              }
            }
          }
          // this.temp.appId = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.flag = 0
          saveGroup(data).then(response => {
            this.list.unshift(response.body.itimsGroupDTO)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.gmtModified = new Date()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          const data = {
            'body': {
              "itimsGroupDTO":{
                "id": this.temp.id,
                "groupName": this.temp.groupName,
                "isDeleted":"0",
                "remark": this.temp.remark
              }
            }
          }
          updateGroup(data).then(response => {
            const businessDTO = response.body.itimsGroupDTO;
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, tempData)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该分组信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

            const data = {
                'body': {
                    "itimsGroupDTO":{
                      "id": row.id
                    }
                  }
                }
                deleteItimsGroup(data).then(response => {
                  const itimsGroupDTO = response.body.itimsGroupDTO;
                  for (const v of this.list) {
                    if (v.id === this.temp.id) {
                      const index = this.list.indexOf(v)
                      this.list.splice(index, 1, itimsGroupDTO)
                      break
                    }
                  }
                  this.$notify({
                    title: '成功',
                    message: '删除成功',
                    type: 'success',
                    duration: 2000
                  })
                })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)

      }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    handleDetail(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogDetailVisible = true
    },
    terminalAllocation(rows){
        this.getListN()
        this.groupId = rows.id
        this.dialogAllocationVisible = true
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getListN() {
      this.listLoadingN = true
      const param = {
        'body': {
          "itimsTerminalDTO":{
            "equipmentId":this.listQueryN.equipmentId
          },
          "pageInfo":{
            "page":this.listQueryN.page,
            "pageSize":this.listQueryN.limit
          }
        }
      }
      getTerminalList(param).then(response => {
        this.listN = response.body.itimsTerminalDTOList
        this.totalN = response.body.pageInfo.rowCount
        this.listLoadingN = false
      })
    },
    handleSizeChangeN(val) {
      this.listQueryN.limit = val
      this.getList()
    },
    handleCurrentChangeN(val) {
      this.listQueryN.page = val
      this.getListN()
    },
    handleFilterN() {
      this.listQuery.page = 1
      this.getListN()
    },
    saveGroupEquipment(){
      let arr = []
      this.multipleSelection.forEach(row =>{
        arr.push(row.id)
      })
      const param = {
        'body': {
          "equipmentGroupDTO":{
            "groupId": this.groupId,
            "equipmentIdList": arr
          }
        }
      }
      saveEquipmentGroupList(param).then(response => {
        this.$notify({
          title: '成功',
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
        this.dialogAllocationVisible = false
      })
    },
    terminalDetailAllocation(row){
      this.groupId = row.id
      this.dialogAllocationDetailVisible = true
      this.getListDetail()
    },
    getListDetail() {
      this.listLoadingdetail = true
      const param = {
        'body': {
          "itimsTerminalDTO":{
            "id": this.groupId
          }
        }
      }
      getTerminalListByGroupId(param).then(response => {
        this.listdetail = response.body.itimsTerminalDTOList
        this.listLoadingdetail = false
      })
    },
  }
}
</script>
